<template>
  <div class="footprints p-6">
    <div class="mb-6 flex justify-between items-center">
      <div>
        <h2 class="text-xl font-semibold text-gray-800">我的足迹</h2>
        <p class="text-gray-500 text-sm mt-1">您最近浏览过的商品</p>
      </div>
      <div class="flex items-center gap-4">
        <el-button type="danger" plain @click="handleClearAll" :disabled="!footprintItems.length">
          <el-icon><Delete /></el-icon>
          清空足迹
        </el-button>
        <el-radio-group v-model="viewMode" size="small">
          <el-radio-button label="list">
            <el-icon><List /></el-icon>
          </el-radio-button>
          <el-radio-button label="grid">
            <el-icon><Grid /></el-icon>
          </el-radio-button>
        </el-radio-group>
      </div>
    </div>

    <!-- Empty State -->
    <el-empty
      v-if="!footprintItems.length"
      description="暂无浏览记录"
      class="mt-8"
    >
      <el-button type="primary" @click="$router.push('/')">
        去逛逛
      </el-button>
    </el-empty>

    <!-- List View -->
    <template v-else>
      <!-- Date Groups -->
      <div v-for="group in groupedFootprints" :key="group.date" class="mb-8">
        <div class="flex items-center justify-between mb-4">
          <h3 class="text-lg font-medium text-gray-700">{{ group.date }}</h3>
          <el-button 
            type="danger" 
            link 
            @click="handleClearByDate(group.date)"
          >
            清除当日足迹
          </el-button>
        </div>

        <!-- List Mode -->
        <div v-if="viewMode === 'list'" class="space-y-4">
          <div
            v-for="item in group.items"
            :key="item.id"
            class="bg-white rounded-lg shadow-sm p-4 flex gap-6 group hover:shadow-md transition-shadow"
          >
            <!-- Product Image -->
            <router-link 
              :to="`/product/${item.id}`"
              class="shrink-0 w-40 h-40 overflow-hidden rounded-lg border border-gray-100"
            >
              <img 
                :src="item.mainPic || 'https://picsum.photos/seed/product/160/160'" 
                :alt="item.title"
                class="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
                @error="handleImageError"
              >
            </router-link>

            <!-- Product Info -->
            <div class="flex-1 min-w-0">
              <div class="flex items-start justify-between mb-2">
                <div class="flex-1">
                  <router-link 
                    :to="`/product/${item.id}`"
                    class="text-lg font-medium text-gray-900 hover:text-blue-600 line-clamp-2"
                  >
                    {{ item.title }}
                  </router-link>
                  <p class="text-sm text-gray-500 mt-1">{{ item.subTitle }}</p>
                </div>
                <div class="text-sm text-gray-500 whitespace-nowrap ml-4">
                  最近访问：{{ formatTime(item.lastVisitTime) }} 访问次数：{{ item.visitCount }}
                </div>
              </div>

              <!-- Tags -->
              <div class="flex flex-wrap gap-2 mb-3">
                <el-tag size="small" type="info" effect="light">{{ item.gCategory }}</el-tag>
                <el-tag size="small" type="warning" effect="light">{{ item.qCategory }}</el-tag>
              </div>

              <!-- Details -->
              <div class="grid grid-cols-2 gap-x-4 gap-y-2 text-sm mb-3">
                <div class="text-gray-500">规格：{{ item.goodsSpec }}</div>
                <div class="text-gray-500">生产厂家：{{ item.manufacturer }}</div>
                <div class="text-gray-500">批准文号：{{ item.approvalNo }}</div>
                <div class="text-gray-500">包装单位：{{ item.unit }}</div>
              </div>

              <!-- Price and Actions -->
              <div class="flex items-center justify-between mt-2">
                <div class="flex items-baseline gap-2">
                  <span class="text-xl font-semibold text-red-500">{{ formatPriceAuth(item.price, !!userStore.token, userStore.userInfo?.discount) }}</span>
                  <span class="text-sm text-gray-500">库存: <span :class="getStockStatusClass(item.storNum)">{{ getStockStatusText(item.storNum) }}</span></span>
                </div>
                <div class="flex items-center gap-2">
                  <el-button 
                    type="primary" 
                    size="small" 
                    @click="handleAddToCart(item)"
                    :disabled="addingToCartIds.has(item.goodsId)"
                    :loading="addingToCartIds.has(item.goodsId)"
                  >
                    <el-icon v-if="!addingToCartIds.has(item.goodsId)"><ShoppingCart /></el-icon>
                    {{ addingToCartIds.has(item.goodsId) ? '添加中...' : '加入购物车' }}
                  </el-button>
                  <el-button type="danger" plain size="small" @click="handleDelete(item.id)">
                    <el-icon><Delete /></el-icon>
                    删除
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- Grid Mode -->
        <div v-else class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          <div
            v-for="item in group.items"
            :key="item.id"
            class="bg-white rounded-lg shadow-sm overflow-hidden group hover:shadow-md transition-shadow"
          >
            <!-- Product Image -->
            <router-link :to="`/product/${item.id}`" class="block relative pt-[100%]">
              <img 
                :src="item.mainPic || 'https://picsum.photos/seed/product/300/300'" 
                :alt="item.title"
                class="absolute inset-0 w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
                @error="handleImageError"
              >
            </router-link>

            <!-- Product Info -->
            <div class="p-4">
              <div class="mb-2">
                <router-link 
                  :to="`/product/${item.id}`"
                  class="text-base font-medium text-gray-900 hover:text-blue-600 line-clamp-2"
                >
                  {{ item.title }}
                </router-link>
                <div class="flex items-center justify-between mt-1">
                  <div class="text-sm text-gray-500">{{ item.manufacturer }}</div>
                  <div class="text-xs text-gray-400">{{ formatTime(item.lastVisitTime) }}</div>
                </div>
              </div>

              <!-- Tags -->
              <div class="flex flex-wrap gap-1 mb-2">
                <el-tag size="small" type="info" effect="plain">{{ item.gCategory }}</el-tag>
                <el-tag size="small" type="warning" effect="plain">{{ item.qCategory }}</el-tag>
              </div>

              <!-- Price and Actions -->
              <div class="flex items-center justify-between mt-3">
                <span class="text-lg font-semibold text-red-500">{{ formatPriceAuth(item.price, !!userStore.token, userStore.userInfo?.discount) }}</span>
                <div class="flex items-center gap-1">
                  <el-button 
                    type="primary" 
                    circle 
                    size="small"
                    @click="handleAddToCart(item)"
                    :disabled="addingToCartIds.has(item.goodsId)"
                    :loading="addingToCartIds.has(item.goodsId)"
                  >
                    <el-icon><ShoppingCart /></el-icon>
                  </el-button>
                  <el-button 
                    type="danger" 
                    plain 
                    circle 
                    size="small"
                    @click="handleDelete(item.id)"
                  >
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Load More -->
      <div v-if="hasMore" class="text-center mt-8">
        <el-button :loading="loading" @click="loadMore">加载更多</el-button>
      </div>
    </template>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete, List, Grid, ShoppingCart } from '@element-plus/icons-vue'
import { useFootprintStore } from '@/stores/footprint'
import { useCartStore } from '@/stores/cart'
import { useUserStore } from '@/stores/user'
import { getStockStatusText, getStockStatusClass } from '@/lib/stockUtils'
import { formatPriceAuth } from '@/lib/utils'
import type { FootprintGoods } from '@/types/footprint'

const footprintStore = useFootprintStore()
const cartStore = useCartStore()
const userStore = useUserStore()
const viewMode = ref('list')
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)

// Add to cart loading states
const addingToCartIds = ref<Set<string>>(new Set())

const footprintItems = computed(() => footprintStore.footprintItems)
const hasMore = computed(() => {
  return footprintItems.value.length < footprintStore.total
})

// Format time
function formatTime(time: string | undefined) {
  if (!time) return ''
  const date = new Date(time)
  const hours = date.getHours().toString().padStart(2, '0')
  const minutes = date.getMinutes().toString().padStart(2, '0')
  return `${hours}:${minutes}`
}

// Group footprints by date
const groupedFootprints = computed(() => {
  const groups: { [key: string]: FootprintGoods[] } = {}
  
  footprintItems.value.forEach(item => {
    const date = new Date(item.lastVisitTime || '').toLocaleDateString('zh-CN')
    if (!groups[date]) {
      groups[date] = []
    }
    groups[date].push(item)
  })

  return Object.entries(groups).map(([date, items]) => ({
    date,
    items
  })).sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime())
})

// Load more data
async function loadMore() {
  if (loading.value) return
  
  try {
    loading.value = true
    currentPage.value++
    await footprintStore.fetchFootprintList(currentPage.value, pageSize.value)
  } catch (error) {
    console.error('Failed to load more footprints:', error)
    ElMessage.error('加载失败，请重试')
  } finally {
    loading.value = false
  }
}

// Delete single footprint
async function handleDelete(id: number) {
  try {
    await ElMessageBox.confirm('确定要删除这条浏览记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await footprintStore.removeFromFootprint(id)
    ElMessage.success('删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Failed to delete footprint:', error)
      ElMessage.error('删除失败，请重试')
    }
  }
}

// Clear footprints by date
async function handleClearByDate(date: string) {
  try {
    await ElMessageBox.confirm('确定要清除这一天的浏览记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    const itemsToDelete = groupedFootprints.value
      .find(group => group.date === date)
      ?.items.map(item => item.id) || []
    
    await Promise.all(itemsToDelete.map(id => footprintStore.removeFromFootprint(id)))
    ElMessage.success('清除成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Failed to clear footprints:', error)
      ElMessage.error('清除失败，请重试')
    }
  }
}

// Clear all footprints
async function handleClearAll() {
  try {
    await ElMessageBox.confirm('确定要清空所有浏览记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await footprintStore.clearFootprints()
    ElMessage.success('清空成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Failed to clear all footprints:', error)
      ElMessage.error('清空失败，请重试')
    }
  }
}

// Add to cart
async function handleAddToCart(item: FootprintGoods) {
  // Prevent multiple clicks
  if (addingToCartIds.value.has(item.goodsId)) {
    return;
  }

  try {
    // Set loading state
    addingToCartIds.value.add(item.goodsId);
    // 验证商品是否支持拆零
    if (item.midpack > 1 && item.isMidpackSaleDisabled === 1) {
      // 不支持拆零的中包装商品，按midpack数量下单
      const success = await cartStore.addItemToCart(item.goodsId, item.midpack)
      if (success) {
        ElMessage.success(`已加入购物车（中包装：${item.midpack}${item.unit}）`)
      } else {
        ElMessage.error('加入购物车失败，请重试')
      }
    } else {
      // 支持拆零或件包装商品，按1个下单
      const success = await cartStore.addItemToCart(item.goodsId, 1)
      if (success) {
        ElMessage.success('已加入购物车')
      } else {
        ElMessage.error('加入购物车失败，请重试')
      }
    }
  } catch (error) {
    console.error('Failed to add to cart:', error)
    ElMessage.error('加入购物车失败，请重试')
  } finally {
    // Always remove from loading state
    addingToCartIds.value.delete(item.goodsId);
  }
}

// Handle image error
function handleImageError(e: Event) {
  const target = e.target as HTMLImageElement
  if (target) {
    target.src = '/images/no.jpg'
  }
}

// Initial data load
onMounted(async () => {
  try {
    loading.value = true
    await footprintStore.fetchFootprintList(currentPage.value, pageSize.value)
  } catch (error) {
    console.error('Failed to load footprints:', error)
    ElMessage.error('加载失败，请重试')
  } finally {
    loading.value = false
  }
})
</script>

<style scoped>
.el-radio-button :deep(.el-icon) {
  margin-right: 0;
}

.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
</style> 